<?php
namespace app\index\controller;

use app\common\model\User as UserModel;
use think\Session;
use think\Controller;

class Oauth extends Controller
{
    protected $user_model;
    protected $_appid ;
    protected $_appsecret;

    public function _initialize(){
        parent::_initialize();
        $this->user_model = new UserModel;
        /*
         * wxb128109a167b1024
7f0c57ce51af1e6323d55de12f00c5f8
         * */
        $this->_appid = 'wxb128109a167b1024';
        $this->_appsecret = '7f0c57ce51af1e6323d55de12f00c5f8';
    }

    public function index(){
        $code = $_GET['code'];
        $state = $_GET['state'];
        if (empty($code)) $this->error('授权失败');
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='. $this->_appid.'&secret='.$this->_appsecret.'&code='.$code.'&grant_type=authorization_code';
        $token = json_decode(httpRequest($token_url),true);
        
        if (isset($token['errcode'])) {
            echo '<h1>错误：</h1>'.$token['errcode'];
            echo '<br/><h2>错误信息：</h2>'.$token['errmsg'];
            exit;
        }

        /**
         *
            { "access_token":"ACCESS_TOKEN",
            "expires_in":7200,
            "refresh_token":"REFRESH_TOKEN",
            "openid":"OPENID",
            "scope":"SCOPE" }
         */

        //如果需要可以使用refresh_token进行刷新access_token，refresh_token有效期为30天，当refresh_token失效之后，需要用户重新授权
        // $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
        // //转成对象
        // $access_token = json_decode(file_get_contents($access_token_url));
        // if (isset($access_token->errcode)) {
        //     echo '<h1>错误：</h1>'.$access_token->errcode;
        //     echo '<br/><h2>错误信息：</h2>'.$access_token->errmsg;
        //     exit;
        // }

        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token['access_token'].'&openid='.$token['openid'].'&lang=zh_CN';
        //转成对象
        $user_info = json_decode(httpRequest($user_info_url),true);
        if (isset($user_info['errcode'])) {
            echo '<h1>错误：</h1>'.$user_info['errcode'];
            echo '<br/><h2>错误信息：</h2>'.$user_info['errmsg'];
            exit;
        }

        /**
            {"openid":" OPENID",
            " nickname": NICKNAME,
            "sex":"1",
            "province":"PROVINCE"
            "city":"CITY",
            "country":"COUNTRY",
            "headimgurl":    "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
            "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
            "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
            }
         */

        //储存用户信息  判断用户是否存在, 存在就直接访问数据库的资料, 不存在就创建, 并返回实时的资料
        if(!($user = $this->user_model->where('openid',$user_info['openid'])->find())){
            $user_info['origin'] = 'weixin_web';
            $result = $this->user_model->allowField(true)->save($user_info);
            if($result){
                //把用户信息存入session里面
                session::set('user',$user_info);
                $this->redirect('index/game/index');
            }
        }else{
            $this->user_model->where('openid',$user_info['openid'])->update(['last_login_time' => date('Y-m-d H:i:s') , 'last_login_ip' => getIP()]);
            session::set('user',$user);
            $this->redirect('index/game/index');
        }

        /*打印用户信息  测试案例  星座项目
        * */
//         $nickname = $user_info->nickname;
        // $sex  = $user_info->sex;
        // $headimgurl = $user_info->headimgurl;
        //$user_url = ''http://weixing.lazhuwang.com.cn/Home/Member/base_img?nickname='.$nickname.'&sex='.$sex.'&headimgurl='.$headimgurl';
        // $user_url = 'http://shop.yougou520.cn/Mobile/index';
        // echo '';
        // echo '<meta http-equiv="refresh" content="0.1;url= '.$user_url.'">';
        //echo '<pre>';
        //print_r($user_info);
        //echo '</pre>';
    }

    public function dayoff(){
        $code = $_GET['code'];
        $state = $_GET['state'];
        if (empty($code)) $this->error('授权失败');
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='. $this->_appid.'&secret='.$this->_appsecret.'&code='.$code.'&grant_type=authorization_code';
        $token = json_decode(httpRequest($token_url),true);

        if (isset($token['errcode'])) {
            echo '<h1>错误：</h1>'.$token['errcode'];
            echo '<br/><h2>错误信息：</h2>'.$token['errmsg'];
            exit;
        }

        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token['access_token'].'&openid='.$token['openid'].'&lang=zh_CN';
        //转成对象
        $user_info = json_decode(httpRequest($user_info_url),true);
        if (isset($user_info['errcode'])) {
            echo '<h1>错误：</h1>'.$user_info['errcode'];
            echo '<br/><h2>错误信息：</h2>'.$user_info['errmsg'];
            exit;
        }

        //储存用户信息  判断用户是否存在, 存在就直接访问数据库的资料, 不存在就创建, 并返回实时的资料
        if(!($user = $this->user_model->where('openid',$user_info['openid'])->find())){
            $user_info['origin'] = 'weixin_web';
            $result = $this->user_model->allowField(true)->save($user_info);
            if($result){
                //把用户信息存入session里面
                session::set('user',$user_info);
                $this->redirect('index/dayoff/index');
            }
        }else{
            $this->user_model->where('openid',$user_info['openid'])->update(['last_login_time' => date('Y-m-d H:i:s') , 'last_login_ip' => getIP()]);
            session::set('user',$user);
            $this->redirect('index/dayoff/index');
        }

    }
    // 中秋贺卡
    public function mid(){
        $code = $_GET['code'];
        $state = $_GET['state'];
        if (empty($code)) $this->error('授权失败');
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='. $this->_appid.'&secret='.$this->_appsecret.'&code='.$code.'&grant_type=authorization_code';
        $token = json_decode(httpRequest($token_url),true);

        if (isset($token['errcode'])) {
            echo '<h1>错误：</h1>'.$token['errcode'];
            echo '<br/><h2>错误信息：</h2>'.$token['errmsg'];
            exit;
        }

        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token['access_token'].'&openid='.$token['openid'].'&lang=zh_CN';
        //转成对象
        $user_info = json_decode(httpRequest($user_info_url),true);
        if (isset($user_info['errcode'])) {
            echo '<h1>错误：</h1>'.$user_info['errcode'];
            echo '<br/><h2>错误信息：</h2>'.$user_info['errmsg'];
            exit;
        }

        //储存用户信息  判断用户是否存在, 存在就直接访问数据库的资料, 不存在就创建, 并返回实时的资料
        if(!($user = $this->user_model->where('openid',$user_info['openid'])->find())){
            $user_info['origin'] = 'weixin_web';
            $result = $this->user_model->allowField(true)->save($user_info);
            if($result){
                //把用户信息存入session里面
                session::set('user',$user_info);
                $this->redirect('index/red/midAutumn');
            }
        }else{
            $this->user_model->where('openid',$user_info['openid'])->update(['last_login_time' => date('Y-m-d H:i:s') , 'last_login_ip' => getIP()]);
            session::set('user',$user);
            $this->redirect('index/red/midAutumn');
        }

    }
}